package banmuoi.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;

import banmuoi.entity.Admin;
import banmuoi.util.HibernateUtil;
import banmuoi.util.WebUtil;

@WebServlet("/account.do")
public class AccountAction extends SecurityAction{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String value = checkLogin(req, resp);
		if(value != null){
			System.out.println(value);
			
			if(value.equals("1") || value.equals("3"))//Admin or productManager
				req.getRequestDispatcher("admin/CategoryAdmin.jsp").forward(req, resp);
			else if (value.equals("2")) {//CustomerCare
				req.getRequestDispatcher("admin/CustomerAdmin.jsp").forward(req, resp);
			}
			else if (value.equals("4")) {//orderManager
				req.getRequestDispatcher("admin/Order.jsp").forward(req, resp);
			}
		}	
		else {
			req.getRequestDispatcher("admin/Login.jsp").forward(req, resp);
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//tạo cookie
		String user = req.getParameter("txtUser");
		String pass = req.getParameter("txtPass");
		String remember = req.getParameter("chkRemember");
		
		Session session = HibernateUtil.openSession();
		String hql = "FROM Admin WHERE name='"+user+"' AND password='"+pass+"'";
		Query query = session.createQuery(hql);
		
		//System.out.println(query.uniqueResult());
		if(query.uniqueResult() != null){
			Admin ad = (Admin) query.uniqueResult();
			int roleId = ad.getPermission().getId();
			//1 - tạo cookie
			String name = "isAdmin";
			String value = String.valueOf(roleId);
			Cookie newCookie = new Cookie(name, value);
			
			//2 - thiết lập thuộc tính
			if(remember != null){
				int maxAge = 60*60;//1 tiếng
				newCookie.setMaxAge(maxAge);
			}
			else {
				newCookie.setMaxAge(60*2);//2 phút
			}
			//3 - gửi cookie về client
			resp.addCookie(newCookie);
			
			//4 - link đến trang quản lý
			req.setAttribute("errorLogin", "Login successfull! <a href='account.do'>Đến trang quản lý</a>");
			
		}
		else {
			req.setAttribute("errorLogin", "Invalid user or password!");
		}	
		doGet(req, resp);	
	}
}
